package toDo.app.controllers;

import interfaces.ICentralManager;
import android.app.AlertDialog;
import android.content.Intent;
import toDo.app.R;
import toDo.app.models.RequestCodes;
import toDo.app.models.User;

public class CentralManagerResultController {
	private ICentralManager activity;
	private Class<?> transition;
	
	public CentralManagerResultController(ICentralManager activity, Class<?> transition) {
		this.activity = activity;
		this.transition = transition;
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch(requestCode) {
			case RequestCodes.login:// the idea is to create a user and use
									// that for queries
				processLoginEvent(resultCode, data);
				break;
			case RequestCodes.register:
				processRegisterEvent(resultCode, data);
				break;
		}
	}

	public void processLoginEvent(int resultCode, Intent data) {
		if (resultCode != ICentralManager.RESULT_OK)
			return;
		if (data != null) {
			activity.setUser(User.getUserFromIntent(data));
			if (activity.getUser() != null && activity.getUser().isValid()) {
				activity.startActivityForResult(
						User.putUserIntoIntent(new Intent(activity, transition), activity.getUser()),
						RequestCodes.main);
			}
		} else {
			activity.setStatusText(activity.getString(R.string.blank));
		}
	}

	public void processRegisterEvent(int resultCode, Intent data) {
		if (resultCode != ICentralManager.RESULT_OK)
			return;
		activity.setUser(User.getUserFromIntent(data));
		if (activity.getUser() == null) {
			// this is for testing purposes, replace with something more
			// appropriate
		} else if (activity.getUser().isValid()) {
			new AlertDialog.Builder(activity).setTitle(R.string.success).setMessage(R.string.registerSuccess)
					.setNeutralButton(R.string.ok, null).show();
		} else {
			new AlertDialog.Builder(activity).setTitle(R.string.error).setMessage(R.string.registerFailed)
					.setNeutralButton(R.string.ok, null).show();
		}
		activity.setStatusText(activity.getString(R.string.blank));
	}
}
